import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Calculator extends StatefulWidget {
  const Calculator({Key? key}) : super(key: key);

  @override
  _CalculatorState createState() => _CalculatorState();
}

class _CalculatorState extends State<Calculator> {
  String _result = "0";
  String _expression = "";
  double _firstNumber = 0;
  String _operation = "";
  bool _isNewInput = true;
  List<String> _history = [];

  @override
  void initState() {
    super.initState();
    _loadHistory();
  }

  void _loadHistory() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _history = prefs.getStringList('calculationHistory') ?? [];
    });
  }

  void _saveHistory() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList('calculationHistory', _history);
  }

  void _addToHistory(String calculation) {
    setState(() {
      _history.insert(0, calculation);
      if (_history.length > 10) {
        _history.removeLast();
      }
    });
    _saveHistory();
  }

  void _appendNumber(String number) {
    setState(() {
      if (_isNewInput) {
        _result = number;
        _isNewInput = false;
        if (_operation.isEmpty) {
          _expression = '';
        }
      } else {
        _result += number;
      }
    });
  }

  void _setOperation(String operation) {
    if (_operation.isNotEmpty && !_isNewInput) {
      _calculate();
    } else if (_result == '-') {
      _result = '0';
    }
    _operation = operation;
    _firstNumber = double.parse(_result);
    _isNewInput = true;
    _expression = '$_result $_operation';
  }

  void _calculate() {
    if (_operation.isNotEmpty) {
      setState(() {
        double secondNumber = double.parse(_result);
        double result;
        switch (_operation) {
          case '+':
            result = _firstNumber + secondNumber;
            break;
          case '-':
            result = _firstNumber - secondNumber;
            break;
          case '×':
            result = _firstNumber * secondNumber;
            break;
          case '÷':
            result = _firstNumber / secondNumber;
            break;
          case '%':
            result = _firstNumber % secondNumber;
            break;
          default:
            return;
        }
        _expression = '$_firstNumber $_operation $secondNumber =';
        _result = _formatResult(result);
        _addToHistory('$_expression $_result');
        _firstNumber = result;
        _operation = '';
        _isNewInput = false;
      });
    }
  }

  void _reset() {
    setState(() {
      _result = '0';
      _operation = '';
      _firstNumber = 0;
      _isNewInput = true;
      _expression = '';
    });
  }

  void _backspace() {
    setState(() {
      if (_result.length > 1) {
        _result = _result.substring(0, _result.length - 1);
      } else {
        _result = '0';
        _isNewInput = true;
      }
    });
  }

  Widget _buildButton(String buttonText, {Color? color}) {
    return Expanded(
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: color ?? Colors.grey[300],
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
          padding: const EdgeInsets.all(20),
        ),
        onPressed: () => _buttonPressed(buttonText),
        child: Text(
          buttonText,
          style: const TextStyle(fontSize: 24, color: Colors.black),
        ),
      ),
    );
  }

  void _handleMinus() {
    if (_isNewInput) {
      _result = '-';
      _isNewInput = false;
    } else {
      _setOperation('-');
    }
  }

  void _buttonPressed(String buttonText) {
    switch (buttonText) {
      case 'C':
        _reset();
        break;
      case '+/-':
        _handleMinus();
        break;
      case '%':
      case '÷':
      case '×':
      case '-':
      case '+':
        _setOperation(buttonText);
        break;
      case '=':
        _calculate();
        break;
      case '.':
        _appendNumber(buttonText);
        break;
      default:
        _appendNumber(buttonText);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 2,
              child: Container(
                padding: const EdgeInsets.all(20),
                alignment: Alignment.bottomRight,
                child: Text(
                  _result,
                  style: const TextStyle(
                    fontSize: 60,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
            Expanded(
              flex: 5,
              child: Container(
                padding: const EdgeInsets.all(10),
                child: Column(
                  children: [
                    Row(
                      children: [
                        _buildButton("C", color: Colors.grey),
                        _buildButton("+/-", color: Colors.grey),
                        _buildButton("%", color: Colors.grey),
                        _buildButton("÷", color: Colors.grey),
                      ],
                    ),
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        _buildButton("7"),
                        _buildButton("8"),
                        _buildButton("9"),
                        _buildButton("×", color: Colors.orange),
                      ],
                    ),
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        _buildButton("4"),
                        _buildButton("5"),
                        _buildButton("6"),
                        _buildButton("-", color: Colors.orange),
                      ],
                    ),
                    SizedBox(height: 10),
                    Row(
                      children: [
                        _buildButton("1"),
                        _buildButton("2"),
                        _buildButton("3"),
                        _buildButton("+", color: Colors.orange),
                      ],
                    ),
                    SizedBox(height: 10),
                    Row(
                      children: [
                        _buildButton("0", color: Colors.grey[300]),
                        _buildButton("."),
                        _buildButton("=", color: Colors.orange),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

String _formatResult(double result) {
  if (result == result.roundToDouble()) {
    return result.round().toString();
  }
  return result.toString();
}
